package com.study.bigwork.homework.controller;

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.gson.Gson;
import com.study.bigwork.entity.Homework;

import com.study.bigwork.homework.service.HomeworkService;


@Controller
@RequestMapping("/homework")
public class HomeworkController {
	@Resource
	private HomeworkService homeworkService;
	
	@RequestMapping(value="/getHomeworks/{tag}/{homeworkType}",method=RequestMethod.GET)
	public void getHomeworks(HttpServletRequest request,HttpServletResponse response,@PathVariable("tag") String tag,@PathVariable("homeworkType") String homeworkType) throws IOException{
		// 设置编码方式
		request.setCharacterEncoding("utf-8");
		// 设置返回数据格式和编码
		response.setContentType("application/json;charset=utf-8");
		String tags=null;
		String homeworkTypes=null;
		PrintWriter out = response.getWriter();
		if ("waitCorrect".equals(tag)) {
			tags = "待批改";
		} else if ("isCorrecting".equals(tag)) {
			tags = "批改中";
		} else if ("hasCorrected".equals(tag)) {
			tags = "批改完成";
		}

		if ("math".equals(homeworkType)) {
			homeworkTypes = "数学";
		} else {
			homeworkTypes = "英语";
		}
		List<Homework> homeworks=homeworkService.getHomeworks(tags, homeworkTypes);
		System.out.println("666" + Arrays.asList(homeworks));
		Gson gson=new Gson();
		String responseMessage=null;
		responseMessage=gson.toJson(homeworks);
		System.out.println("对象转换为json"+responseMessage);
		out.print(responseMessage);

	}
	@RequestMapping(value="/getHomeworks/{id}",method=RequestMethod.GET)
	public void getHomeworks(HttpServletRequest request,HttpServletResponse response,@PathVariable("id") String id) throws IOException{
		// 设置编码方式
		request.setCharacterEncoding("utf-8");
		// 设置返回数据格式和编码
		response.setContentType("application/json;charset=utf-8");

		// 定义StringBuffer变量
		String responseMessage = null;
		PrintWriter out = response.getWriter();
		String homeworkType = "";
		String homeworkTypes = "";
		String tag = "";
		String tags = "";
		String sql = "";
		homeworkType = request.getParameter("homeworkType");
		tag = request.getParameter("tag");
		int id1=-1;
		if (null != id) {
			 id1 = Integer.parseInt(id);
			 System.out.println("id"+id);
		}
		List<Homework> homeworks=homeworkService.getHomeworks(id1);
		System.out.println("666" + Arrays.asList(homeworks));
		Gson gson=new Gson();
		responseMessage=gson.toJson(homeworks);
		System.out.println("对象转换为json"+responseMessage);
		out.print(responseMessage);

	}
	//添加作业信息
	@RequestMapping(value="/addHomework",method=RequestMethod.POST)
	public void addHomework(HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
				request.setCharacterEncoding("utf-8");
				//设置返回数据格式和编码
		        response.setContentType("application/json;charset=utf-8");
		        
		        //定义StringBuffer变量
		      	StringBuffer stringBuffer = new StringBuffer();
		        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
		        String line = null, responseMessage = null;
		        
		        //输出流
		        PrintWriter out = response.getWriter();
		        
		        //读取信息时会发生IO异常
		        try{
		            //BufferedReader为缓冲读取流
		            BufferedReader bufferedReader = request.getReader();
		            while((line = bufferedReader.readLine()) != null){
		                stringBuffer.append(line);
		            }
		            System.out.println(stringBuffer);
		            
		        }catch(IOException e){
		            e.printStackTrace();
		        }
		        //将json数据转为String
		        Gson gson = new Gson();
		        Homework homework =gson.fromJson(stringBuffer.toString(), Homework.class);
		        homework.setScored("false");
		        boolean b = false;
		        System.out.println(homework.toString());
		        //调用MenuService类中isExistUser方法访问数据库，并返回查询结果
		        b = homeworkService.addHomework(homework);
		        responseMessage = gson.toJson(b);
		        
		        System.out.println("对象转为json " + responseMessage);
		        //输出流将信息返回
		        out.print(responseMessage);
	}
	
	//接收安卓端发来的作业图片
	@RequestMapping(value="/uploadHomeworkImage/{imgName}",method=RequestMethod.POST)
	public void uploadHomeworkImage(@PathVariable("imgName") String imgName,HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
				request.setCharacterEncoding("utf-8");
				//设置返回数据格式和编码
				response.setContentType("application/json;charset=utf-8");
				
				// 接收客户端上传的文件
				System.out.println(imgName);
				String address = request.getServletContext().getRealPath("/");
				 String path ="images/"+ imgName+".jpg";
				InputStream in = request.getInputStream();
				FileOutputStream fos = new FileOutputStream(address + path);
				byte[] buffer = new byte[1024];
				int len = 0;
				while ((len = in.read(buffer)) != -1) {
					fos.write(buffer, 0, len);
				}
				fos.flush();
				fos.close();
				in.close();
				response.getWriter().append("上传成功");
	}

	//接收安卓端发来的作业信息(家长端)
	@RequestMapping(value="/updateHomeworkInfo/{id}/{grade}/{tag}",method=RequestMethod.POST)
	public void updateHomeworkInfo(@PathVariable("id") String id,@PathVariable("grade") String grade,@PathVariable("tag") String tag,
			HttpServletRequest request,HttpServletResponse response) throws IOException {
		// 设置编码方式
				request.setCharacterEncoding("utf-8");
				//设置返回数据格式和编码
		        response.setContentType("application/json;charset=utf-8");
		        
		        //定义StringBuffer变量
		      	StringBuffer stringBuffer = new StringBuffer();
		        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
		        String line = null, responseMessage = null;
		        
		        //输出流
		        PrintWriter out = response.getWriter();
		        
		        //读取信息时会发生IO异常
		        try{
		            //BufferedReader为缓冲读取流
		            BufferedReader bufferedReader = request.getReader();
		            while((line = bufferedReader.readLine()) != null){
		                stringBuffer.append(line);
		            }
		            System.out.println(stringBuffer);
		            
		        }catch(IOException e){
		            e.printStackTrace();
		        }
		        int id1 = Integer.parseInt(id);
		        int grade1 = Integer.parseInt(grade);
		        int tag1 = Integer.parseInt(tag);
		        System.out.println("获取到的id"+id1);
		        System.out.println("获取到的grade"+grade1);
		        System.out.println("获取到的tag"+tag1);
		        String scored = "true";
		        //将json数据转为String
		        Gson gson = new Gson();
		        Homework homework = new Homework();
		        homework.setId(id1);
		        homework.setGrade(grade1);
		        homework.setScored(scored);
		        boolean b = false;
		        System.out.println(homework.toString());
		        //调用MenuService类中isExistUser方法访问数据库，并返回查询结果
		        b = this.homeworkService.updateHomework(homework);
		        responseMessage = gson.toJson(b);
		        
		        System.out.println("对象转为json " + responseMessage);
		        //输出流将信息返回
		        out.print(responseMessage);
	}
	
	@RequestMapping(value="/updateHomeworkTag/{id}/{teacherid}",method=RequestMethod.GET)
	public void updateHomeworkTag(@PathVariable("id") String id,@PathVariable("teacherid") String teacherid,HttpServletRequest request,HttpServletResponse response) throws IOException {
	
		// 设置编码方式
				request.setCharacterEncoding("utf-8");
				//设置返回数据格式和编码
		        response.setContentType("application/json;charset=utf-8");
		        
		        //定义StringBuffer变量
		      	StringBuffer stringBuffer = new StringBuffer();
		        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
		        String line = null, responseMessage = null;
		        
		        //输出流
		        PrintWriter out = response.getWriter();
		        
		        //读取信息时会发生IO异常
		        try{
		            //BufferedReader为缓冲读取流
		            BufferedReader bufferedReader = request.getReader();
		            while((line = bufferedReader.readLine()) != null){
		                stringBuffer.append(line);
		            }
		            System.out.println(stringBuffer);
		            
		        }catch(IOException e){
		            e.printStackTrace();
		        }
		        
		        int id1 = Integer.parseInt(id);
		        int teacherid1 = Integer.parseInt(teacherid);
		        System.out.println("updateHomeworkTag中id="+id1+" teacher_id="+teacherid);
		        
		        boolean b = false;
		     
	
		        b = homeworkService.updateHomeworkTag(id1,teacherid1);
		        responseMessage = b+"";
		        
		        System.out.println("UpdateHomeworkTag   对象转为json " + responseMessage);
		        //输出流将信息返回
		        out.print(responseMessage);
		        
	}
	//教师端更新作业信息
	@RequestMapping(value="/updateWorkInfo/{tag}",method=RequestMethod.POST)
	public void updateWorkInfo(@PathVariable("tag") String tag, HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		// 设置编码方式
				request.setCharacterEncoding("utf-8");
				//设置返回数据格式和编码
		        response.setContentType("application/json;charset=utf-8");
		        
		        //定义StringBuffer变量
		      	StringBuffer stringBuffer = new StringBuffer();
		        //line保存读取请求信息的当前一行，responseMessage为响应信息，返回信息
		        String line = null, responseMessage = null;
		        
		        //输出流
		        PrintWriter out = response.getWriter();
		        
		        //读取信息时会发生IO异常
		        try{
		            //BufferedReader为缓冲读取流
		            BufferedReader bufferedReader = request.getReader();
		            while((line = bufferedReader.readLine()) != null){
		                stringBuffer.append(line);
		            }
		            System.out.println("updateWorkInfo   "+stringBuffer);
		            
		        }catch(IOException e){
		            e.printStackTrace();
		        }
		        
		        int tag1 = Integer.parseInt(tag);
		        
		        
		        //将json数据转为String
		        Gson gson = new Gson();
		        Homework homework =gson.fromJson(stringBuffer.toString(), Homework.class);
		        boolean b = false;
		        System.out.println(homework.toString());
		        //调用MenuService类中isExistUser方法访问数据库，并返回查询结果
		       
		        b = homeworkService.updateHomeworkInfo(tag1,homework);
		        responseMessage = gson.toJson(b);
		        
		        System.out.println("UpdateWorkInfo   对象转为json " + responseMessage);
		        //输出流将信息返回
		        out.print(responseMessage);
	}
	//教师端更新作业返回图片
	@RequestMapping(value="/uploadHomeworkResultImage/{imgName}",method=RequestMethod.POST)
	public void uploadHomeworkResultImage(@PathVariable("imgName") String imgName, HttpServletRequest request,HttpServletResponse response) throws IOException {
		
		request.setCharacterEncoding("utf-8");
		//设置返回数据格式和编码
		response.setContentType("application/json;charset=utf-8");
		
		// 接收客户端上传的文件
		System.out.println("uploadHomeworkResultImage resultImgage"+imgName);
		String address = request.getServletContext().getRealPath("/");
		 String path ="images/"+ imgName+".jpg";
		InputStream in = request.getInputStream();
		FileOutputStream fos = new FileOutputStream(address + path);
		byte[] buffer = new byte[1024];
		int len = 0;
		while ((len = in.read(buffer)) != -1) {
			fos.write(buffer, 0, len);
		}
		fos.flush();
		fos.close();
		in.close();
		response.getWriter().append("上传成功");
	}
	//是否是批改过的作业
	@RequestMapping(value="/getIsCorrectingHomework/{tag}/{teacherId}",method=RequestMethod.GET)
	public void getIsCorrectingHomework(@PathVariable("tag") String tag,@PathVariable("teacherId") String teacherId,HttpServletRequest request,HttpServletResponse response) throws IOException {
	
		// 设置编码方式
		request.setCharacterEncoding("utf-8");
		// 设置返回数据格式和编码
		response.setContentType("application/json;charset=utf-8");

		// 定义StringBuffer变量
		String responseMessage = null;

		// 输出流
		PrintWriter out = response.getWriter();
		int teacherId1;
		
		teacherId1 = Integer.parseInt(teacherId);
		

		if ("waitCorrect".equals(tag)) {
			tag = "待批改";
		} else if ("isCorrecting".equals(tag)) {
			tag = "批改中";
		} else if ("hasCorrected".equals(tag)) {
			tag = "批改完成";
		}
		List<Homework> homeworks=new ArrayList<Homework>();
		homeworks = homeworkService.getHomeworks(teacherId1,tag);
		System.out.println("isCorrect   " + Arrays.asList(homeworks));
		Gson gson = new Gson();
		responseMessage = gson.toJson(homeworks);

		System.out.println("isCorrect  对象转为json " + responseMessage);
		// 输出流将信息返回
		out.print(responseMessage);
	}
}
